import React, {useState} from 'react';
import {
  NavigationContainer,
  RouteProp,
  NavigationState,
} from '@react-navigation/native';
import SplashScreen from 'react-native-splash-screen';
import {
  CardStyleInterpolators,
  createStackNavigator,
  HeaderStyleInterpolators,
  StackNavigationProp,
  TransitionPresets,
} from '@react-navigation/stack';
import BottomTabs from './BottomTabs';
import Detail from '../pages/Detail';
import {Platform, StyleSheet, StatusBar} from 'react-native';
import Category from '@/pages/Category/index';
import Album from '@/pages/Album/index';
import Animated from 'react-native-reanimated';
import Icon from '@/assets/iconfont/index';
import PlayView from './../pages/Views/PlayView';
import {getActiveRouteName, navigationRef, useDidMount} from '@/utils/index';
import Login from './../pages/Login';

export type RootStackParamList = {
  BottomTabs: {
    screen?: string;
  };
  category: undefined;
  Album: {
    item: {
      id: string;
      title: string;
      image: string;
    };
  };
};
let Stack = createStackNavigator<RootStackParamList>();
export type RootStackNavigation = StackNavigationProp<RootStackParamList>;
/*{
  Navigator
  Screen
}*/
// type Route = RouteProp<RootStackParamList, 'BottomTabs'> & {
//   state?: TabNavigationState,
// };
// interface IProps {
//   navigation: RootStackNavigator;
//   route: RouteProp<RootStackParamList, 'BottomTabs'> & {
//     state?: TabNavigationState<>;
//   };
// }

const Navigator = () => {
  const [routeName, setRouteName] = useState('');
  const onStateChange = (state: NavigationState | undefined) => {
    if (typeof state !== 'undefined') {
      const routeName = getActiveRouteName(state);
      setRouteName(routeName);
    }
  };
  useDidMount(() => {
    SplashScreen.hide();
  });
  return (
    <NavigationContainer ref={navigationRef} onStateChange={onStateChange}>
      <ModalStackScreen />
      <PlayView routeName={routeName} />
    </NavigationContainer>
  );
};
// 页面枚举
export type ModalStackParamList = {
  Root: undefined;
  Detail: {
    id: string;
  };
  Login: undefined;
};

//重新定义一个最外层路由  使详情页面独立  出现时Root保持状态
const ModalStack = createStackNavigator<ModalStackParamList>();

export type ModalStackNavigation = StackNavigationProp<ModalStackParamList>;

const ModalStackScreen = () => {
  return (
    <ModalStack.Navigator
      mode="modal"
      headerMode="screen" //标识每一个页面都有自己独立的标题栏
      screenOptions={{
        headerTitleAlign: 'center', //标题居中
        gestureEnabled: true, //开始手势关闭
        ...TransitionPresets.ModalSlideFromBottomIOS,
        headerBackTitleVisible: false,
        headerTintColor: '#333', //标题颜色
      }}>
      <ModalStack.Screen
        name="Root"
        component={RootStackScreen}
        options={{headerShown: false}} //使头部标题不显示
      />
      <ModalStack.Screen
        name="Detail"
        component={Detail}
        options={{
          headerTintColor: '#FFF', //header返回按键颜色
          headerTitle: '', //标题
          headerTransparent: true, //使标题栏透明（且此设定不占位）
          cardStyle: {backgroundColor: '#807c66'}, //整个页面背景颜色
          headerBackImage: ({tintColor}) => (
            <Icon
              name="icon-down"
              size={30}
              color={tintColor}
              style={styles.headerBackImage}
            />
          ),
        }}
      />
      <ModalStack.Screen
        name="Login"
        component={Login}
        options={{headerTitle: '登录'}}
      />
    </ModalStack.Navigator>
  );
};

const RootStackScreen = () => {
  const getAlbumOptions = ({
    route,
  }: {
    route: RouteProp<RootStackParamList, 'Album'>;
  }) => {
    return {
      headerTitle: route.params.item.title, //设置页面标题
      headerTransparent: true, //标题栏设置透明（不占位置）
      headerTitleStyle: {
        opacity: 0,
      },
      headerBackground: () => <Animated.View style={styles.headerBackground} />,
    };
  };
  return (
    <Stack.Navigator
      headerMode="float" //标题栏模式  float为共用一个
      screenOptions={{
        headerTitleAlign: 'center', //标题栏文字对齐模式
        headerStyleInterpolator: HeaderStyleInterpolators.forUIKit, //使标题栏切换时拥有透明渐变效果
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS, //使切换页面时拥有统一的切换效果  为ios的横向切片效果
        gestureEnabled: true, //使安卓开启滑动路由栈（除首页）关闭页面（ios默认开启）
        gestureDirection: 'horizontal', //使安卓滑动关闭方向为水平方向（ios默认水平方向，安卓默认垂直方向）
        ...Platform.select({
          // 选择性设置  设置安卓
          android: {
            headerStatusBarHeight: StatusBar.currentHeight, //设置顶部高度  使其不在进入时可能高度为0时闪烁 ios无影响
          },
        }),
        headerBackTitleVisible: false, //设置返回按钮文字不显示  为图标（android无影响）
        headerTintColor: '#333', //返回按钮与标题文字颜色
        headerStyle: {
          // backgroundColor: 'red', //顶部栏颜色
          //美化安卓端使与ios相似
          ...Platform.select({
            android: {
              elevation: 0, //使安卓端投影消失（主要为界面切换时投影过于丑陋）
              borderBottomWidth: StyleSheet.hairlineWidth, //设置导航栏下边框border（美化）
            },
          }),
        },
      }}>
      <Stack.Screen
        options={{headerTitle: '首页'}}
        name="BottomTabs"
        component={BottomTabs}
      />
      <Stack.Screen
        options={{headerTitle: '分类'}}
        name="category"
        component={Category}
      />
      <Stack.Screen options={getAlbumOptions} name="Album" component={Album} />
    </Stack.Navigator>
  );
};

const styles = StyleSheet.create({
  headerBackground: {
    flex: 1,
    backgroundColor: '#FFF',
    opacity: 0,
  },
  headerBackImage: {
    // marginVertical: 5,
    marginHorizontal: Platform.OS === 'android' ? 0 : 8,
  },
});

export default Navigator;
